package mumu.android.lib.view.webview;

import java.util.Timer;
import java.util.TimerTask;

import mumu.android.view.webview1;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MWebViewClient extends WebViewClient {
	private final String TAG = "dd";
	private String mUrl = "";
	private Handler handler;
	// 超时时间
	public static final int TIME_OUT = 200000;
	private Timer timer;
	private WebView mWebView;

	public MWebViewClient(Handler handler) {
		this.handler = handler;
	}

	@Override
	public boolean shouldOverrideUrlLoading(WebView view, String url) {
		Log.d(TAG, url);
		/*
		 * 这个地方拦截地址，做业务处理
		 */
		view.loadUrl(url);

		return true;
	}

	@Override
	public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

		if (mUrl.equals(failingUrl)) {
			Log.d(TAG, "errorCode=" + errorCode + ",description=" + description + ",failingUrl=" + failingUrl);
			view.stopLoading();
			view.setEnabled(false);
			view.clearView();
			Message msg = handler.obtainMessage();// 发送通知，加入线程
			// 通知加载自定义异常页面
			if (errorCode == ERROR_TIMEOUT)
				msg.what = WebViewFrame.LOAD_ERROR_TIMEOUT;
			else
				msg.what = WebViewFrame.LOAD_ERROR_DEFAULT;
			handler.sendMessage(msg);// 通知发送！
		}
	}

	private Handler pageloadhHandler = new Handler() {

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				onReceivedError(mWebView, ERROR_TIMEOUT, "The connection to the server was unsuccessful.", mUrl);
				timer.cancel();
				timer.purge();
				break;
			}
		}

	};

	@Override
	public void onPageStarted(final WebView view, String url, Bitmap favicon) {
		Log.d(TAG, "onPageStarted=" + url);
		this.mUrl = url;
		this.mWebView = view;
		timer = new Timer();
		TimerTask tt = new TimerTask() {
			@Override
			public void run() {
				/*
				 * 超时后,首先判断页面加载进度,超时并且进度小于100,就执行超时后的动作
				 */
				if (view.getProgress() < 100) {
					Log.d("testTimeout", "timeout...........");
					pageloadhHandler.sendEmptyMessage(1);

				}
			}
		};
		timer.schedule(tt, TIME_OUT, 1);
		super.onPageStarted(view, url, favicon);
	}

	/**
	 * 1.程序只认为DOM加载完成就完成了，正在加载的图片不在这个范围之内。
	 * 2.如果在JS文件中又动态去加载其他html或js数据，onPageFinished方法会在所有的JS执行完毕后才调用。
	 */
	@Override
	public void onPageFinished(WebView view, String url) {
		Log.d(TAG, "onPageFinished=" + url);
		Log.d(TAG, "+++++++++++++++++++++++++" + view.getProgress());
		timer.cancel();
		timer.purge();
		super.onPageFinished(view, url);
	}

	@Override
	public void onLoadResource(WebView view, String url) {
		Log.d(TAG, "onLoadResource=" + url);
		super.onLoadResource(view, url);
	}
}
